<template>
    <div>
        <!-- 表头分页查询条件， shadow="never" 指定 card 卡片组件没有阴影 -->
        <el-card shadow="never" class="mb-5">
            <!-- flex 布局，内容垂直居中 -->
            <div class="flex items-center">
                <el-text>分类名称</el-text>
                <div class="ml-3 w-52 mr-5">
                    <el-input v-model="searchCategoryName" placeholder="请输入（模糊查询）" />
                </div>

                <el-text>创建日期</el-text>
                <div class="ml-3 w-30 mr-5">
                    <!-- 日期选择组件（区间选择） -->
                    <el-date-picker v-model="pickDate" type="daterange" range-separator="至" start-placeholder="开始时间"
                        end-placeholder="结束时间" size="default" :shortcuts="shortcuts" @change="datepickerChange" />
                </div>

                <el-button type="primary" class="ml-3" :icon="Search" @click="getTableData">查询</el-button>
                <el-button class="ml-3" :icon="RefreshRight" @click="reset">重置</el-button>
            </div>
        </el-card>
        <el-card shadow="never">
            <!-- 新增按钮 -->
            <div class="mb-5">
                <el-button type="primary" @click="addCategoryBtnClick">
                    <el-icon class="mr-1">
                        <Plus />
                    </el-icon>
                    新增</el-button>
            </div>

            <!-- 分页列表 -->
            <el-table :data="tableData" :default-sort="{ prop: 'categoryName', order: 'descending' }" border stripe
                style="width: 100%" v-loading="tableLoading">
                <el-table-column type="selection" width="45" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="id" label="分类编号" width="180" />
                <el-table-column prop="categoryName" label="分类名称" sortable width="180">
                    <template #default=scope>
                        <el-tag type="primary" round>{{ scope.row.categoryName }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="articlesTotal" label="文章数" width="120" />
                <el-table-column prop="createTime" label="创建时间" width="180" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="danger" size="small" @click="deleteCategorySubmit(scope.row)">
                            <el-icon class="mr-1">
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="mt-10 flex justify-center">
                <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[5, 10, 20, 50]"
                    :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="getTableData" />
            </div>
        </el-card>


        <!-- 添加分类 -->
        <!-- <el-dialog v-model="dialogVisible" title="添加文章分类" width="40%" :draggable="true" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <el-form ref="formRef" :rules="rules" :model="form">
                <el-form-item label="分类名" prop="name" label-width="100px">
                    输入框组件
                    <el-input size="large" v-model="form.name" placeholder="请输入分类名(1-16个字符范围内)" maxlength="16" show-word-limit clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit">
                        提交
                    </el-button>
                </span>
            </template>
        </el-dialog> -->

        <FormDialog ref="formDialogRef" title="添加文章分类" destroyOnClose @submit="onSubmit">
            <el-form ref="formRef" :rules="rules" :model="form">
                <el-form-item label="分类名" prop="name" label-width="100px">
                    <!-- 输入框组件 -->
                    <el-input size="large" v-model="form.name" placeholder="请输入分类名(1-16个字符范围内)" maxlength="16"
                        show-word-limit clearable />
                </el-form-item>
            </el-form>
        </FormDialog>
    </div>
</template>

<script setup>
// 引入所需图标
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { dateEquals } from 'element-plus';
import moment from 'moment';
import { ref, reactive } from 'vue';

//表格数据加载动画
const tableLoading = ref(false)

// 分页查询的分类名称
const searchCategoryName = ref('')
// 日期
const pickDate = ref('')

//起始时间
const startDate = reactive({})
//结束时间
const endDate = reactive({})
//监听日期组件改变事件，并将开始结束时间设置到变量中
const datepickerChange = (e) => {
    startDate.value = moment(e[0]).format('YYYY-MM-DD')
    endDate.value = moment(e[1]).format('YYYY-MM-DD')
    console.log("开始时间：" + startDate.value + " 结束时间：" + endDate.value)
}

//近期时间
const shortcuts = [
    {
        text: '最近一天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 1)
            return [start, end]
        }
    },
    {
        text: '最近三天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 3)
            return [start, end]
        }
    },
    {
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 7)
            return [start, end]
        }
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 30)
            return [start, end]
        }
    },
    {
        text: '最近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 90)
            return [start, end]
        }
    },
    {
        text: '最近六个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 180)
            return [start, end]
        }
    },
    {
        text: '最近一年',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 365)
            return [start, end]
        }
    }
]

import { addCategory, deleteCategory, getCategoryPageList } from '@/api/admin/category';
import { showMessage, showModel } from '@/composables/utils';
// 表格数据         
const tableData = ref([])
// 当前页码，给了一个默认值 1
const current = ref(1)
// 总数据量，给了个默认值 0
const total = ref(0)
// 每页显示的数据量，给了个默认值 10
const size = ref(10)
 // 每页展示数量变更事件
 const handleSizeChange = (chooseSize) => {
    size.value = chooseSize
    getTableData()
}
//获取分页数据
function getTableData() {
    //显示表格loading
    tableLoading.value = true
    //调用后台接口，传入所需参数
    const reqParams = {
        current: current.value,
        size: size.value,
        startDate: startDate.value,
        endDate: endDate.value,
        categoryName: searchCategoryName.value
    }
    getCategoryPageList(reqParams).then((res) => {
        if (res.success == true) {
            //获取数据成功
            console.log('获取分类分页数据success')
            tableData.value = res.data
            current.value = res.pageIndex
            size.value = res.size
            total.value = res.total
            
        }
    }).finally(() => {tableLoading.value = false})
}

//重置
function reset() {
    searchCategoryName.value = ''
    pickDate.value = ''
    startDate.value = null
    endDate.value = null
}
//进入页面获取数据
getTableData()

//添加分类名
//会话框状态
const dialogVisible = ref(false)
//表单
const formRef = ref(null)
//表单实体
const form = reactive({
    name: ''
})

//规则校验
const rules = {
    name: [
        {
            required: true,
            message: "分类名不能为空",
            trigger: "blur"
        },
        { min: 1, max: 16, message: '分类名称字数要求大于 1 个字符，小于 16 个字符', trigger: 'blur' }
    ]
}
//提交
function onSubmit() {
    //验证表单
    formRef.value.validate((valid) => {
        if (!valid) {
            console.log("表单验证不通过 for 添加分类")
            return false
        }
        //显示提交按钮
        formDialogRef.value.showBtnLoading()
        //请求添加分类接口
        addCategory(form).then((res) => {
            if (res.success == true) {
                console.log("category add success")
                showMessage('添加分类成功')
                //清空表单数据
                form.name = ''
                //隐藏对话框
                // dialogVisible.value = false
                formDialogRef.value.close()
                //重新获取数据
                getTableData()
            } else {
                showMessage(res.message, 'error')
            }
        }).finally(() => formDialogRef.value.closeBtnLoading())
    })
}

//删除对应的标签
function deleteCategorySubmit(row) {
    //获取对应的id
    console.log(row)
    let id = row.id;

    showModel("是否确认删除分类：" + row.categoryName, "warning", "温馨提示：").then(() => {
        //发送删除请求
        deleteCategory({ id: id }).then((res) => {
            if (res.success == true) {
                let message = "分类字段" + row.categoryName + "已删除！"
                console.log(message)
                showMessage(message)
                //刷新数据
                getTableData()
            } else {
                let message = res.message
                showMessage(message, 'warning')
            }
        })

    }).catch(() => {
        let message = "删除分类操作已取消！删除分类名：" + row.categoryName
        showMessage(message, 'error')
    })

}

import FormDialog from '@/components/FormDialog.vue';

const formDialogRef = ref(null)
//新增分类按钮点击事件
const addCategoryBtnClick = () => {
    formDialogRef.value.open()
}
</script>